package com.fancy.application.sys.log.service.impl;

import cn.hutool.core.io.FileUtil;
import lombok.extern.log4j.Log4j2;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.springframework.stereotype.Service;


import java.io.File;
import java.lang.reflect.Method;

@Log4j2
@Service("sysLogLocationService")
public class SysLogLocationService {

    private String dbPath = "";

    public SysLogLocationService() {
        dbPath = SysLogLocationService.class.getResource("/ip2region.db").getPath();
    }

    public String getLocationByIp(String Ip){

        File file = FileUtil.file(this.dbPath);
        if ( file.exists() == false ) {
            log.warn("Error: Invalid ip2region.db file");
            return "";
        }
        if ( Util.isIpAddress(Ip) == false ) {
            log.warn("Error: Invalid ip address");
            return "";
        }

        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        //DbSearcher.BINARY_ALGORITHM //Binary
        //DbSearcher.MEMORY_ALGORITYM //Memory
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            //define the method
            Method method = null;
            switch ( algorithm )
            {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            DataBlock dataBlock = null;
            dataBlock  = (DataBlock) method.invoke(searcher, Ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
